#include "ImageListBox.h"
#include "FlowLayout.h"
#include <QtGui>

ImageIcon::ImageIcon(QWidget *parent) : QAbstractButton(parent) {
    imageEnabled = true;
    margin = QSize(2, 2);
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    setCheckable(true);
    setAutoExclusive(true);
    connect(this, SIGNAL(clicked()), SLOT(clickedSlot()));
}

void ImageIcon::setPixmap(const QPixmap &pix) {
    this->pix = pix;
    updateGeometry();
}

void ImageIcon::setImageEnabled(bool on) {
    if (imageEnabled != on) {
        imageEnabled = on;
        update();
    }
}

QSize ImageIcon::sizeHint() const {
    return pix.size() + margin*2.0;
}

void ImageIcon::clickedSlot() {
    emit clicked(id);
}

void ImageIcon::paintEvent(QPaintEvent *event) {
    QPainter paint(this);
    paint.fillRect(0, 0, width(), height(), QBrush(Qt::white));
    if (!imageEnabled) paint.setOpacity(.5);
    paint.drawPixmap(margin.width(), margin.height(), pix);
    if (isChecked()) {
        paint.setOpacity(.5);
        paint.setBrush(QBrush(palette().highlight().color()));
        paint.drawRect(0, 0, width()-1, height()-1);
    }
}

ImageListBox::ImageListBox(QWidget *parent) : QScrollArea(parent) {
    selected = NULL;
    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    setFocusPolicy(Qt::NoFocus);
    widget = new QWidget(this);
    setWidget(widget);
    layout = new FlowLayout(widget);
    layout->setMargin(3);
    layout->setSpacing(3);
    //layout->addStretch(0);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setWidgetResizable(true);
}

void ImageListBox::addIcon(ImageIcon *icon) {
    widgets.append(icon);
    connect(icon, SIGNAL(clicked(QVariant)), SLOT(iconClicked(QVariant)));
    //layout->insertWidget(layout->count()-1, icon);
    layout->addWidget(icon);
    QScrollArea::widget()->resize(widget->layout()->sizeHint());
}

void ImageListBox::iconClicked(QVariant id) {
    selected = dynamic_cast< ImageIcon * >(sender());
    emit clicked(id);
}
